﻿
/*
 =====================================================
 * Copyright © 2022 IceToad All rights reserved.
 * 作者: IceToad
 * 创建时间: 2022/11/09 10:09:09
 * 版本: v1.0.1
 * 版权说明: 引用或转载请注明源
 * ----------------------------------------------------
 * 文件名: MD5Decryption.cs
 * 程序集: YYEnAndDecryption
 * 文件功能: MD5加密。
 * CSDN：https://blog.csdn.net/weixin_44312699
 * Gitee：https://gitee.com/icetoads
 * 语雀：https://www.yuque.com/icetoad
 * 公众号：【冰蟾DotNet】（后台可留言）
 * ----------------------------------------------------
 * 说明：
 * 本项目提供功能有限，难免有考虑不到的情况，如发现错误或有什么建议，欢迎指正
 ======================================================
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace YYEnAndDecryption
{
    /// <summary>
    /// MD5加密位数
    /// </summary>
    public enum MD5EncryptBit
    {
        MD5Encrypt16 = 0,
        MD5Encrypt32 = 1
    }
    /// <summary>
    /// MD5加密类
    /// </summary>
    public class MD5Decryption
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="TXTstrint">要加密的字符串</param>
        /// <param name="bit">加密串位数，默认16位</param>
        /// <param name="key">密钥，在字符串前拼接，加密拼接后新字符串</param>
        /// <param name="IsRemove">是否去除“-”</param>
        /// <returns>返回加密字符串</returns>
        public static string MD5Encrypt(string TXTstrint, MD5EncryptBit bit = MD5EncryptBit.MD5Encrypt16, string key = "", bool IsRemove = true)
        {
            string StrResult = "";

            try
            {
                var md5 = new MD5CryptoServiceProvider();
                byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(key + TXTstrint));

                if (bit == MD5EncryptBit.MD5Encrypt16)
                {
                    StrResult = BitConverter.ToString(result, 4, 8);
                }
                else if (bit == MD5EncryptBit.MD5Encrypt32)
                {
                    StrResult = BitConverter.ToString(result);
                }
                else
                {
                    YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5Encrypt]:参数，加密位数不存在！bit=" + bit.ToString());
                }

                if (IsRemove)
                {
                    StrResult = StrResult.Replace("-", "");
                }
            }
            catch (Exception ex)
            {
                YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5Encrypt]", ex);
            }
            return StrResult;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="TXTstrint">要加密的字符串</param>
        /// <param name="bit">加密串位数，默认16位</param>
        /// <param name="key">密钥，在字符串前拼接，加密拼接后新字符串</param>
        /// <param name="IsRemove">是否去除“-”</param>
        /// <returns>返回加密字符串</returns>
        public static string MD5Encrypt2(string TXTstrint, MD5EncryptBit bit = MD5EncryptBit.MD5Encrypt16, string key = "", bool IsRemove = true)
        {
            string StrResult = "";
            try
            {
                MD5 md5 = MD5.Create();
                byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(key + TXTstrint));
                for (int i = 0; i < result.Length; i++)
                {
                    StrResult = StrResult + result[i].ToString("X2") + "-";
                }

                if (bit == MD5EncryptBit.MD5Encrypt16)
                {
                    StrResult = StrResult.Substring(0, StrResult.Length - 1).Substring(12, 23);
                }
                else if (bit == MD5EncryptBit.MD5Encrypt32)
                {
                    StrResult = StrResult.Substring(0, StrResult.Length - 1);
                }
                else
                {
                    YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5Encrypt2]:参数，加密位数不存在！bit=" + bit.ToString());
                }

                if (IsRemove)
                {
                    StrResult = StrResult.Replace("-", "");
                }
            }
            catch (Exception ex)
            {

                YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5Encrypt2]", ex);
            }

            return StrResult;
        }

        /// <summary>
        /// MD5加密文件
        /// </summary>
        /// <param name="fileUrl">要加密的文件路径</param>
        /// <param name="bit">加密串位数，默认16位</param>
        /// <param name="IsRemove">是否去除“-”</param>
        /// <returns>返回加密字符串</returns>
        public static string MD5EncryptFile(string fileUrl, MD5EncryptBit bit = MD5EncryptBit.MD5Encrypt16, bool IsRemove = true)
        {
            string StrResult = "";
            try
            {
                //判断文件是否存在
                if (string.IsNullOrWhiteSpace(fileUrl) || !File.Exists(fileUrl))
                {
                    return StrResult;
                }
                //获取文件
                using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffur = new byte[fs.Length];

                    fs.Read(buffur, 0, (int)fs.Length);
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                    MD5 md5 = MD5.Create();
                    byte[] result = md5.ComputeHash(buffur);

                    if (bit == MD5EncryptBit.MD5Encrypt16)
                    {
                        StrResult = BitConverter.ToString(result, 4, 8);
                    }
                    else if (bit == MD5EncryptBit.MD5Encrypt32)
                    {
                        StrResult = BitConverter.ToString(result);
                    }
                    else
                    {
                        YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5EncryptFile]:参数，加密位数不存在！bit=" + bit.ToString());
                    }

                    if (IsRemove)
                    {
                        StrResult = StrResult.Replace("-", "");
                    }
                }
            }
            catch (Exception ex)
            {

                YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5EncryptFile]", ex);
            }

            return StrResult;
        }

        /// <summary>
        /// MD5加密文件
        /// </summary>
        /// <param name="bt">要加密的数据</param>
        /// <param name="bit">加密串位数，默认16位</param>
        /// <param name="IsRemove">是否去除“-”</param>
        /// <returns>返回加密字符串</returns>
        public static string MD5EncryptFile(byte[] bt, MD5EncryptBit bit = MD5EncryptBit.MD5Encrypt16, bool IsRemove = true)
        {
            string StrResult = "";
            try
            {
                if (bt == null)
                {
                    return StrResult;
                }
                MD5 md5 = MD5.Create();
                byte[] result = md5.ComputeHash(bt);

                if (bit == MD5EncryptBit.MD5Encrypt16)
                {
                    StrResult = BitConverter.ToString(result, 4, 8);
                }
                else if (bit == MD5EncryptBit.MD5Encrypt32)
                {
                    StrResult = BitConverter.ToString(result);
                }
                else
                {
                    YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5EncryptFile]:参数，加密位数不存在！bit=" + bit.ToString());
                }

                if (IsRemove)
                {
                    StrResult = StrResult.Replace("-", "");
                }

            }
            catch (Exception ex)
            {

                YYLogHelper.LogHelper.WriteLogError(Environment.NewLine + "[YYEnAndDecryption.MD5Decryption.MD5EncryptFile]", ex);
            }

            return StrResult;
        }
    }
}
